package com.floreantpos.ui.model;

import com.floreantpos.main.Application;
import com.floreantpos.model.*;
import com.floreantpos.model.dao.MenuGroupDAO;
import com.floreantpos.model.dao.MenuItemDAO;
import com.floreantpos.model.dao.TaxDAO;
import com.floreantpos.swing.ComboBoxModel;
import com.floreantpos.swing.DoubleDocument;
import com.floreantpos.swing.FixedLengthDocument;
import com.floreantpos.swing.MessageDialog;
import com.floreantpos.ui.BeanEditor;
import com.floreantpos.ui.dialog.BeanEditorDialog;
import com.floreantpos.ui.dialog.ConfirmDeleteDialog;
import com.floreantpos.util.POSUtil;
import com.googlecode.floreo.ecf.bematech.BematechMP2100;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import org.hibernate.Hibernate;
import org.hibernate.Session;

public class MenuItemForm extends BeanEditor implements ActionListener {
  
public static String SERVICE_ITEM = "Serviço";
public static String PRODUCT_ITEM = "Produto";

public static String AL = "%";
public static String FF = "Subst. Tributária";
public static String II = "Isento";
  
private Double currentTaxRate = Double.valueOf(0);
private Double newTaxRate = Double.valueOf(0);

private Integer currentQtyOnHand = 0;
private Integer newQtyOnHand = 0;
private Integer oldQtyOnHand = 0;

private Boolean currentIsUpdateInventory = false;
private Boolean newIsUpdateInventory = false;

private String userName = "";

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

 public MenuItemForm() throws Exception {
    this(new MenuItem());

    tfDiscountRate.setDocument(new DoubleDocument());
  }

  public MenuItemForm(MenuItem menuItem) throws Exception {
    initComponents();

    tfName.setDocument(new FixedLengthDocument(30));

    MenuGroupDAO foodGroupDAO = new MenuGroupDAO();
    List<MenuGroup> foodGroups = foodGroupDAO.findAll();
    cbGroup.setModel(new ComboBoxModel(foodGroups));
    
    cbItemCategory.addItem(PRODUCT_ITEM);
    cbItemCategory.addItem(SERVICE_ITEM);
    
    cbSituacaoEcf.addItem(AL);
    cbSituacaoEcf.addItem(FF);
    cbSituacaoEcf.addItem(II);

    TaxDAO taxDAO = new TaxDAO();
    tax = taxDAO.get(1);

    menuItemModifierGroups = menuItem.getMenuItemModiferGroups();
    menuItemMGListModel = new MenuItemMGListModel();
    tableTicketItemModifierGroups.setModel(menuItemMGListModel);

    btnNewModifierGroup.addActionListener(this);
    btnEditModifierGroup.addActionListener(this);
    btnDeleteModifierGroup.addActionListener(this);

    setBean(menuItem);
  }

  private void initComponents() {

    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    tfName = new com.floreantpos.swing.FixedLengthTextField();
    jLabel4 = new javax.swing.JLabel();
    cbGroup = new javax.swing.JComboBox();
    cbItemCategory = new javax.swing.JComboBox();
    cbSituacaoEcf = new javax.swing.JComboBox();
    btnNewGroup = new javax.swing.JButton();
    btnNewCategory = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    tfPrice = new javax.swing.JFormattedTextField();
    tfQtyOnHand = new javax.swing.JFormattedTextField();
    tfInventoryAdjustment = new javax.swing.JFormattedTextField();
    tfQtyOnHandUpdate = new javax.swing.JFormattedTextField();
    tfAdditionalReference = new javax.swing.JFormattedTextField();
    tfStdCost = new javax.swing.JFormattedTextField();
    tfTaxRate = new javax.swing.JFormattedTextField();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    jLabel11 = new javax.swing.JLabel();
    jLabel12 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    tfDiscountRate = new javax.swing.JTextField();
    chkVisible = new javax.swing.JCheckBox();
    chkBuffet = new javax.swing.JCheckBox();
    chkUpdateInventory = new javax.swing.JCheckBox();
    chkPrintToKitchen = new javax.swing.JCheckBox();
    jPanel2 = new javax.swing.JPanel();
    btnNewModifierGroup = new javax.swing.JButton();
    btnDeleteModifierGroup = new javax.swing.JButton();
    btnEditModifierGroup = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    tableTicketItemModifierGroups = new javax.swing.JTable();

    jLabel1.setText(com.floreantpos.POSConstants.NAME + ":");
    
    jLabel12.setText("Referência:");

    jLabel4.setText(com.floreantpos.POSConstants.GROUP + ":");

    btnNewGroup.setText("...");
    btnNewGroup.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        doCreateNewGroup(evt);
      }
    });
    
    btnNewCategory.setText("...");
    btnNewCategory.setEnabled(false);
    
    jLabel7.setText("Categoria:");

    jLabel3.setText(com.floreantpos.POSConstants.PRICE + ":");

    jLabel6.setText("Custo Std.:");
    
    jLabel8.setText("Alíquota:");
    
    jLabel10.setText("Estoque:");
    
    jLabel11.setText("Aj. Estoque:");

    tfPrice.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfDiscountRate.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfStdCost.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfTaxRate.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfQtyOnHand.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfInventoryAdjustment.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tfQtyOnHandUpdate.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    
    tfQtyOnHandUpdate.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
          if (e.getButton() == 1 && e.getClickCount() == 2) {
            doShowUpdatedTime();
          }
        }
      });

    tfQtyOnHandUpdate.setEnabled(false);
    tfQtyOnHand.setEnabled(false);

    jLabel2.setText(com.floreantpos.POSConstants.DISCOUNT_RATE + ":");

    jLabel5.setText("%");
    jLabel9.setText("%");

    chkVisible.setText(com.floreantpos.POSConstants.VISIBLE);
    chkVisible.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    chkVisible.setMargin(new java.awt.Insets(0, 0, 0, 0));

    chkBuffet.setText("Peso");
    chkBuffet.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    chkBuffet.setMargin(new java.awt.Insets(0, 0, 0, 0));
    
    chkUpdateInventory.setText("Atualizar Estoque");
    chkUpdateInventory.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    chkUpdateInventory.setMargin(new java.awt.Insets(0, 0, 0, 0));    

    chkPrintToKitchen.setText(com.floreantpos.POSConstants.PRINT_TO_KITCHEN);
    chkPrintToKitchen.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    chkPrintToKitchen.setMargin(new java.awt.Insets(0, 0, 0, 0));

    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel7)
                            .add(jPanel1Layout.createSequentialGroup()
                                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(jLabel3)
                                            .add(jLabel6)
                                            .add(jLabel4)
                                            .add(jLabel2)
                                            .add(jLabel8)
                                            .add(jLabel11)
                                            .add(jLabel10)
                                            .add(jLabel12)
                                            .add(jLabel1))
                                    .add(17, 17, 17)
                                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                            .add(tfName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
                                            .add(tfAdditionalReference, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
                                            .add(jPanel1Layout.createSequentialGroup()
                                                    .add(cbGroup, 0, 312, Short.MAX_VALUE)
                                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                                    .add(btnNewGroup))
                                            .add(jPanel1Layout.createSequentialGroup()
                                                    .add(cbItemCategory, 0, 312, Short.MAX_VALUE)
                                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                                    .add(btnNewCategory))                                                                                       
                                            .add(jPanel1Layout.createSequentialGroup()
                                                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, tfDiscountRate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, tfTaxRate, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, tfPrice, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, tfStdCost, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, tfInventoryAdjustment, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                                            .add(org.jdesktop.layout.GroupLayout.TRAILING, tfQtyOnHand, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                                            .add(chkVisible)
                                                            .add(chkBuffet)
                                                            .add(chkPrintToKitchen)
                                                            .add(chkUpdateInventory))
                                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                                            .add(tfQtyOnHandUpdate)
                                                            .add(cbSituacaoEcf)
                                                            .add(jLabel5)
                                                    )))))
                    .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(tfName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel12)
                            .add(tfAdditionalReference, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                    
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel4)
                            .add(btnNewGroup)
                            .add(cbGroup, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                    
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel7)
                            .add(btnNewCategory)
                            .add(cbItemCategory, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                                       
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel3)
                            .add(tfPrice, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel6)
                            .add(tfStdCost, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel11)
                            .add(tfInventoryAdjustment, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                     
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel10)
                            .add(tfQtyOnHandUpdate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(tfQtyOnHand, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                    
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel8)
                            .add(cbSituacaoEcf, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(tfTaxRate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                    
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel2)
                            .add(jLabel5)
                            .add(tfDiscountRate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)                                      
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(chkVisible)
                    .add(chkBuffet)
                    .add(chkPrintToKitchen)
                    .add(chkUpdateInventory)
                    .addContainerGap(157, Short.MAX_VALUE))
    );

    jTabbedPane1.addTab(com.floreantpos.POSConstants.GENERAL, jPanel1);

    btnNewModifierGroup.setText(com.floreantpos.POSConstants.ADD);
    btnNewModifierGroup.setActionCommand("AddModifierGroup");
    btnNewModifierGroup.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnNewModifierGroupActionPerformed(evt);
      }
    });

    btnDeleteModifierGroup.setText(com.floreantpos.POSConstants.DELETE);
    btnDeleteModifierGroup.setActionCommand("DeleteModifierGroup");

    btnEditModifierGroup.setText(com.floreantpos.POSConstants.EDIT);
    btnEditModifierGroup.setActionCommand("EditModifierGroup");

    tableTicketItemModifierGroups.setModel(new javax.swing.table.DefaultTableModel(
            new Object[][]{
              {},
              {},
              {},
              {}
            },
            new String[]{}
    ));
    jScrollPane1.setViewportView(tableTicketItemModifierGroups);

    org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap(280, Short.MAX_VALUE)
                    .add(btnNewModifierGroup)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(btnEditModifierGroup)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(btnDeleteModifierGroup)
                    .addContainerGap())
            .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 377, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(86, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(btnDeleteModifierGroup)
                            .add(btnEditModifierGroup)
                            .add(btnNewModifierGroup))
                    .addContainerGap())
    );

    jTabbedPane1.addTab(com.floreantpos.POSConstants.MODIFIER_GROUPS, jPanel2);

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    );
    layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
                    .addContainerGap())
    );
  }

  private void btnNewModifierGroupActionPerformed(java.awt.event.ActionEvent evt) {

  }

  private void doCreateNewGroup(java.awt.event.ActionEvent evt) {
    MenuGroupForm editor = new MenuGroupForm();
    BeanEditorDialog dialog = new BeanEditorDialog(editor, getParentFrame(), true);
    dialog.open();
    if (!dialog.isCanceled()) {
      MenuGroup foodGroup = (MenuGroup) editor.getBean();
      ComboBoxModel model = (ComboBoxModel) cbGroup.getModel();
      model.addElement(foodGroup);
      model.setSelectedItem(foodGroup);
    }
  }

  private javax.swing.JButton btnDeleteModifierGroup;
  private javax.swing.JButton btnEditModifierGroup;
  private javax.swing.JButton btnNewGroup;
  private javax.swing.JButton btnNewCategory;
  private javax.swing.JButton btnNewModifierGroup;
  private javax.swing.JComboBox cbGroup;
  private javax.swing.JComboBox cbSituacaoEcf;
  private javax.swing.JComboBox cbItemCategory;
  private javax.swing.JCheckBox chkVisible;
  private javax.swing.JCheckBox chkBuffet;
  private javax.swing.JCheckBox chkPrintToKitchen;
  private javax.swing.JCheckBox chkUpdateInventory;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JLabel jLabel10;
  private javax.swing.JLabel jLabel11;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JPanel jPanel2;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JTable tableTicketItemModifierGroups;
  private javax.swing.JTextField tfDiscountRate;
  private com.floreantpos.swing.FixedLengthTextField tfName;
  private javax.swing.JFormattedTextField tfPrice;
  private javax.swing.JFormattedTextField tfAdditionalReference;
  private javax.swing.JFormattedTextField tfQtyOnHandUpdate;
  private javax.swing.JFormattedTextField tfQtyOnHand;
  private javax.swing.JFormattedTextField tfInventoryAdjustment;
  private javax.swing.JFormattedTextField tfStdCost;
  private javax.swing.JFormattedTextField tfTaxRate;
  private List<MenuItemModifierGroup> menuItemModifierGroups;
  private MenuItemMGListModel menuItemMGListModel;
  private DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("pt", "BR")));
  private DecimalFormat integerFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(new Locale("pt", "BR")));
  private Tax tax = new Tax();

  private void doShowUpdatedTime() {
    JOptionPane.showMessageDialog(null, "\nUsuário: " + userName + "\nQtd. Anterior: " + oldQtyOnHand + "\n\n", "Última modificação", JOptionPane.INFORMATION_MESSAGE, null);
  }  
  
  private void addMenuItemModifierGroup() {
    try {
      MenuItemModifierGroupForm form = new MenuItemModifierGroupForm();
      BeanEditorDialog dialog = new BeanEditorDialog(form, getParentFrame(), true);
      dialog.open();
      if (!dialog.isCanceled()) {
        MenuItemModifierGroup modifier = (MenuItemModifierGroup) form.getBean();
        menuItemMGListModel.add(modifier);
      }
    } catch (Exception x) {
      MessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE, x);
    }
  }

  private void editMenuItemModifierGroup() {
    try {
      int index = tableTicketItemModifierGroups.getSelectedRow();
      if (index < 0) {
        return;
      }

      MenuItemModifierGroup menuItemModifierGroup = menuItemMGListModel.get(index);

      MenuItemModifierGroupForm form = new MenuItemModifierGroupForm(menuItemModifierGroup);
      BeanEditorDialog dialog = new BeanEditorDialog(form, getParentFrame(), true);
      dialog.open();
      if (!dialog.isCanceled()) {
        menuItemMGListModel.fireTableDataChanged();
      }
    } catch (Exception x) {
      MessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE, x);
    }
  }

  private void deleteMenuItemModifierGroup() {
    try {
      int index = tableTicketItemModifierGroups.getSelectedRow();
      if (index < 0) {
        return;
      }

      if (ConfirmDeleteDialog.showMessage(this, com.floreantpos.POSConstants.CONFIRM_DELETE, com.floreantpos.POSConstants.CONFIRM) == ConfirmDeleteDialog.YES) {
        menuItemMGListModel.remove(index);
      }
    } catch (Exception x) {
      MessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE, x);
    }
  }

  @Override
  public boolean save() {
    try {
      if (!updateModel()) {
        return false;
      }
      MenuItem menuItem = (MenuItem) getBean();
      MenuItemDAO menuItemDAO = new MenuItemDAO();
      menuItemDAO.saveOrUpdate(menuItem);
    } catch (Exception e) {
      MessageDialog.showError(com.floreantpos.POSConstants.ERROR_MESSAGE, e);
      return false;
    }
    return true;
  }

  @Override
  public void dispose() {
  }

  @Override
  protected void updateView() {
    MenuItem menuItem = (MenuItem) getBean();

    if (menuItem.getId() != null && !Hibernate.isInitialized(menuItem.getMenuItemModiferGroups())) {
      MenuItemDAO dao = new MenuItemDAO();
      Session session = dao.getSession();
      menuItem = (MenuItem) session.merge(menuItem);
      Hibernate.initialize(menuItem.getMenuItemModiferGroups());
      session.close();
    }

    tfName.setText(menuItem.getName());
    tfPrice.setValue(decimalFormat.format(Double.valueOf(menuItem.getPrice())));
    tfStdCost.setValue(decimalFormat.format(Double.valueOf(menuItem.getStdCost())));
    tfDiscountRate.setText(String.valueOf(decimalFormat.format(menuItem.getDiscountRate())));
    tfTaxRate.setText(String.valueOf(decimalFormat.format(menuItem.getTaxRate())));
    tfQtyOnHand.setText(String.valueOf(integerFormat.format(menuItem.getQtyOnHand())));
    tfAdditionalReference.setText(menuItem.getAdditionalReference());
    tfInventoryAdjustment.setText("");
    
    if (menuItem.getQtyOnHandUpdate() == null) {
      tfQtyOnHandUpdate.setText("");
    } else {
      tfQtyOnHandUpdate.setText(dateFormat.format(menuItem.getQtyOnHandUpdate()));
    }
    
    chkVisible.setSelected(menuItem.isVisible());
    chkBuffet.setSelected(menuItem.isBuffet());
    chkPrintToKitchen.setSelected(menuItem.isShouldPrintToKitchen());
    chkUpdateInventory.setSelected(menuItem.isUpdateInventory());
    
    currentTaxRate = menuItem.getTaxRate();
    currentQtyOnHand = menuItem.getQtyOnHand().intValue();
    currentIsUpdateInventory = menuItem.isUpdateInventory();
    oldQtyOnHand = menuItem.getOldQtyOnHand().intValue();
    userName = menuItem.getUserName();

    if (menuItem.isServiceItem()) {
      cbItemCategory.setSelectedItem(SERVICE_ITEM);
    } else {
      cbItemCategory.setSelectedItem(PRODUCT_ITEM);
    }
    
    if (menuItem.getSituacaoEcf().equals("AL")) {
      cbSituacaoEcf.setSelectedItem(AL);
    } else if (menuItem.getSituacaoEcf().equals("FF")) {
      cbSituacaoEcf.setSelectedItem(FF);
    } else if (menuItem.getSituacaoEcf().equals("II")) {
      cbSituacaoEcf.setSelectedItem(II);
    }
    
    if (menuItem.getId() == null) {
      // do nothing
    } else {
      cbGroup.setSelectedItem(menuItem.getParent());
    }
  }

  @Override
  protected boolean updateModel() {
    String itemName = tfName.getText();
    if (POSUtil.isBlankOrNull(itemName)) {
      MessageDialog.showError(com.floreantpos.POSConstants.NAME_REQUIRED);
      return false;
    }
    
    if (itemName.length() > 28) {
      MessageDialog.showError("O Nome deve conter no máximo 28 caracteres.");
      return false;      
    }

    MenuItem menuItem = (MenuItem) getBean();
    menuItem.setName(itemName);
    
    String additionalReference = tfAdditionalReference.getText();
    
    if (additionalReference.length() > 28) {
      MessageDialog.showError("A Referência deve conter no máximo 28 caracteres.");
      return false;      
    }  
    
    menuItem.setAdditionalReference(additionalReference);    
    
    menuItem.setParent((MenuGroup) cbGroup.getSelectedItem());
    
    if (cbItemCategory.getSelectedItem().equals(PRODUCT_ITEM)) {
      menuItem.setServiceItem(Boolean.FALSE);
    } else {
      menuItem.setServiceItem(Boolean.TRUE);
    }
    
    if (cbSituacaoEcf.getSelectedItem().equals(AL)) {
      menuItem.setSituacaoEcf("AL");
    } else if (cbSituacaoEcf.getSelectedItem().equals(FF)) {
      menuItem.setSituacaoEcf("FF");
    } else if (cbSituacaoEcf.getSelectedItem().equals(II)) {
      menuItem.setSituacaoEcf("II");
    }

    if (!tfPrice.getText().isEmpty()) { 
      try {
        menuItem.setPrice(Double.valueOf(decimalFormat.parse(tfPrice.getValue().toString()).doubleValue()));
      } catch (ParseException ex) {
        Logger.getLogger(MenuItemForm.class.getName()).log(Level.SEVERE, null, ex);
        MessageDialog.showError("Valor Inválido");
        return false;      
      }
    }

    if (!tfStdCost.getText().isEmpty()) {    
      try {
        menuItem.setStdCost(Double.valueOf(decimalFormat.parse(tfStdCost.getValue().toString()).doubleValue()));
      } catch (ParseException ex) {
        Logger.getLogger(MenuItemForm.class.getName()).log(Level.SEVERE, null, ex);
        MessageDialog.showError("Custo Std. Inválido");
        return false;      
      }
    }

    menuItem.setTax(tax);
    menuItem.setVisible(chkVisible.isSelected());
    menuItem.setBuffet(chkBuffet.isSelected());
    menuItem.setShouldPrintToKitchen(chkPrintToKitchen.isSelected());
    
    newIsUpdateInventory = chkUpdateInventory.isSelected();
    
    menuItem.setUpdateInventory(newIsUpdateInventory);

    if (!tfTaxRate.getText().isEmpty()) {
      try {
        newTaxRate = decimalFormat.parse(tfTaxRate.getText()).doubleValue();
        menuItem.setTaxRate(newTaxRate);
      } catch (ParseException ex) {
        Logger.getLogger(MenuItemForm.class.getName()).log(Level.SEVERE, null, ex);
        MessageDialog.showError("Alíquota Inválida");
        return false;
      }
    }
    
    if (!tfDiscountRate.getText().isEmpty()) {
      try {
        menuItem.setDiscountRate(decimalFormat.parse(tfDiscountRate.getText()).doubleValue());
      } catch (ParseException ex) {
        Logger.getLogger(MenuItemForm.class.getName()).log(Level.SEVERE, null, ex);
        MessageDialog.showError("Desconto Inválido");
        return false;
      }
    }

    menuItem.setMenuItemModiferGroups(menuItemModifierGroups);

    int menuItemModifierGroupsQty = 0;

    if (menuItem.getMenuItemModiferGroups() != null) {
      menuItemModifierGroupsQty = menuItem.getMenuItemModiferGroups().size();
    }
    
    if (menuItem.isServiceItem() && menuItemModifierGroupsQty != 0) {
      MessageDialog.showError("Itens da Categoria \"Serviço\" não podem conter \"Grupos de Modificações\".");
      return false;      
    }

    if (menuItem.isBuffet() && menuItemModifierGroupsQty != 0) {
      MessageDialog.showError("Itens marcados como \"Peso\" não podem conter \"Grupos de Modificações\".");
      return false;
    }
    
    if (menuItem.isServiceItem() && menuItem.isUpdateInventory()) {
      MessageDialog.showError("Itens da Categoria \"Serviço\" não podem ter o estoque controlado.\nOpção: \"Atualizar Estoque\".");
      return false;
    }    
    
    if (menuItem.isBuffet() && menuItem.isUpdateInventory()) {
      MessageDialog.showError("Itens marcados como \"Peso\" não podem ter o estoque controlado.\nOpção: \"Atualizar Estoque\".");
      return false;
    }    
    
    if (menuItem.getPrice() > 999999.99) {
      MessageDialog.showError("O Valor Máximo permitido é R$ 999.999,99.");
      return false;      
    }
    
    if (menuItem.getPrice() <= 0) {
      MessageDialog.showError("O Valor deve ser maior que R$ 0,00.");
      return false;      
    }
    
    if (menuItem.getStdCost() > 999999.99) {
      MessageDialog.showError("O Custo Std. Máximo permitido é R$ 999.999,99.");
      return false;      
    }
    
    if (menuItem.getStdCost() < 0) {
      MessageDialog.showError("O Custo Std. deve ser maior ou igual a R$ 0,00.");
      return false;      
    }
    
    User user = Application.getCurrentUser();
    if (user != null) {
      userName = user.getFirstName() + " " + user.getLastName();      
    }
    
    if (!currentIsUpdateInventory.equals(newIsUpdateInventory)) {        
      menuItem.setQtyOnHand(Double.valueOf(0));
      menuItem.setQtyOnHandUpdate(new Date()); 
      menuItem.setOldQtyOnHand(currentQtyOnHand.doubleValue());
      menuItem.setUserName(userName);         
    }    
    
    
    if (menuItem.isUpdateInventory() && !tfInventoryAdjustment.getText().isEmpty()) {  
      if (!tfInventoryAdjustment.getText().substring(0, 1).equals("=") && !tfInventoryAdjustment.getText().substring(0, 1).equals("+") && !tfInventoryAdjustment.getText().substring(0, 1).equals("-")) {
        tfInventoryAdjustment.setText("");
        MessageDialog.showError("Estoque Inválido:\n\n"
                + "  Para acresentar itens ao estoque digite \"+\" e a qtd. desejada.\n"
                + "    Ex.: \"+50\" (Acrescenta 50 ao estoque atual)\n\n"
                + "  Para retirar itens do estoque digite \"-\" e a qtd. desejada.\n"
                + "    Ex.: \"-50\" (Retira 50 do estoque atual)\n\n"
                + "  Para ajustar o estoque com uma qtd. específica digite \"=\" e a qtd. desejada.\n"
                + "    Ex.: \"=50\" (Define a qtd. do estoque atual como 50)\n\n");
        return false;        
      } else if (tfInventoryAdjustment.getText().substring(0, 1).equals("=") || tfInventoryAdjustment.getText().substring(0, 1).equals("+") || tfInventoryAdjustment.getText().substring(0, 1).equals("-")) {
        if (!POSUtil.isNumeric(tfInventoryAdjustment.getText().substring(1, tfInventoryAdjustment.getText().length()))) {
          tfInventoryAdjustment.setText("");
          MessageDialog.showError("Estoque Inválido");
          return false;          
        }
        
        try {
          newQtyOnHand = integerFormat.parse(tfInventoryAdjustment.getText().substring(1, tfInventoryAdjustment.getText().length())).intValue();
        } catch (ParseException ex) {
          Logger.getLogger(MenuItemForm.class.getName()).log(Level.SEVERE, null, ex);
          tfInventoryAdjustment.setText("");
          MessageDialog.showError("Estoque Inválido");
          return false;      
        }

        if (tfInventoryAdjustment.getText().substring(0, 1).equals("+")) {
          newQtyOnHand = currentQtyOnHand + newQtyOnHand;
        } else if (tfInventoryAdjustment.getText().substring(0, 1).equals("-")) {
          newQtyOnHand = currentQtyOnHand - newQtyOnHand;
        } else if (tfInventoryAdjustment.getText().substring(0, 1).equals("=")) {
          // do nothing;
        }

        if (newQtyOnHand < 0) {
          tfInventoryAdjustment.setText("");
          MessageDialog.showError("Estoque deve ser maior ou igual a 0.");
          return false;        
        } else {         
          menuItem.setQtyOnHand(newQtyOnHand.doubleValue());
          menuItem.setQtyOnHandUpdate(new Date());
          menuItem.setOldQtyOnHand(currentQtyOnHand.doubleValue());
          menuItem.setUserName(userName);          
        }
      }          
    }

    if (menuItem.getTaxRate() <= 0) {
      MessageDialog.showError("A Alíquota deve ser maior que 0,00 %.");
      return false;      
    }  
    
    if (menuItem.getTaxRate() > 99.99) {
      MessageDialog.showError("A Alíquota deve ser menor que 99,99 %.");
      return false;      
    }     
    
    if (menuItem.getDiscountRate() < 0) {
      MessageDialog.showError("O Desconto deve ser maior ou igual a 0,00 %.");
      return false;        
    }
    
    if (!Application.isTestSystem() && (Application.getECFStatus() != 2 && !currentTaxRate.equals(newTaxRate))) {
      menuItem.setName("!" + itemName);
      menuItem.setVisible(Boolean.FALSE);
      JOptionPane.showMessageDialog(null, "Antes de utilizar o item, sua Alíquota deve ser verificada\nno sistema conectado com a Impressora de Cupom Fiscal.", com.floreantpos.POSConstants.MDS_POS, JOptionPane.INFORMATION_MESSAGE, null);
    }
    
    if (!Application.isTestSystem() && Application.getECFStatus() == 2) {
      
      int rateCategory = 0;
      
      if (menuItem.isServiceItem()) {
        rateCategory = 1;
      } else {
        rateCategory = 0;
      }
      
      String taxRateAsString = "0000";
      
      if (menuItem.getTaxRate() >= 10) {
        taxRateAsString = decimalFormat.format(Double.valueOf(menuItem.getTaxRate())).replace(",", "");
      } else if (menuItem.getTaxRate() >= 0) {
        taxRateAsString = "0" + decimalFormat.format(Double.valueOf(menuItem.getTaxRate())).replace(",", "");
      }
      
      Boolean isTaxRateSet = false;
      
      if (rateCategory == 1) {
        isTaxRateSet = BematechMP2100.retornoAliquotasS().contains(taxRateAsString);
      } else {
        isTaxRateSet = BematechMP2100.retornoAliquotasT().contains(taxRateAsString);
      }
      
      if (!isTaxRateSet) {
        BematechMP2100.programaAliquota(taxRateAsString, rateCategory);
      }
    }    
    
    return true;
  }

  public String getDisplayText() {
    MenuItem foodItem = (MenuItem) getBean();
    if (foodItem.getId() == null) {
      return com.floreantpos.POSConstants.NEW_MENU_ITEM;
    }
    return com.floreantpos.POSConstants.EDIT_MENU_ITEM;
  }

  class MenuItemMGListModel extends AbstractTableModel {

    String[] cn = {com.floreantpos.POSConstants.GROUP_NAME, com.floreantpos.POSConstants.MIN_QUANTITY, com.floreantpos.POSConstants.MAX_QUANTITY};

    MenuItemMGListModel() {
    }

    public MenuItemModifierGroup get(int index) {
      return menuItemModifierGroups.get(index);
    }

    public void add(MenuItemModifierGroup group) {
      if (menuItemModifierGroups == null) {
        menuItemModifierGroups = new ArrayList<MenuItemModifierGroup>();
      }
      menuItemModifierGroups.add(group);
      fireTableDataChanged();
    }

    public void remove(int index) {
      if (menuItemModifierGroups == null) {
        return;
      }
      menuItemModifierGroups.remove(index);
      fireTableDataChanged();
    }

    public void remove(MenuItemModifierGroup group) {
      if (menuItemModifierGroups == null) {
        return;
      }
      menuItemModifierGroups.remove(group);
      fireTableDataChanged();
    }

    public int getRowCount() {
      if (menuItemModifierGroups == null) {
        return 0;
      }

      return menuItemModifierGroups.size();

    }

    public int getColumnCount() {
      return cn.length;
    }

    @Override
    public String getColumnName(int column) {
      return cn[column];
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
      MenuItemModifierGroup menuItemModifierGroup = menuItemModifierGroups.get(rowIndex);

      switch (columnIndex) {
        case 0:
          return menuItemModifierGroup.getModifierGroup().getName();

        case 1:
          return Integer.valueOf(menuItemModifierGroup.getMinQuantity());

        case 2:
          return Integer.valueOf(menuItemModifierGroup.getMaxQuantity());
      }
      return null;
    }
  }

  public void actionPerformed(ActionEvent e) {
    String actionCommand = e.getActionCommand();
    if (actionCommand.equals("AddModifierGroup")) {
      addMenuItemModifierGroup();
    } else if (actionCommand.equals("EditModifierGroup")) {
      editMenuItemModifierGroup();
    } else if (actionCommand.equals("DeleteModifierGroup")) {
      deleteMenuItemModifierGroup();
    }
  }
}
